package com.gyh.thymeleaf.interceptor;

import com.gyh.thymeleaf.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 * @author gyhstart
 * @create 2020/6/25 - 20:18
 **/
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 请求之前调用处理
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = (User) request.getSession().getAttribute("user");
        System.out.println(user);
        if (null != user){
            return true;
        }
        //跳转到登录界面
        response.sendRedirect(request.getContextPath()+"/api/login");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //1,取出start
        long start = (long) request.getAttribute("start");
        //2,得到end
        long end =System.currentTimeMillis();
        //3,记录耗时
        long spendTime = end-start;
        if (spendTime>2000){
            logger.warn("方法耗时严重，请及时处理，耗时："+spendTime);
        }else {
            logger.info("方法耗时"+spendTime+"毫秒，正常");
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.info("================= Interceptor  after ===============");
    }
}
